package com.jiexin.service.impl;

import com.jiexin.dao.dsh.DSHChangeMapper;
import com.jiexin.schedule.ExtractHandler;
import com.jiexin.service.MailService;
import com.jiexin.service.ReadXmlService;
import com.jiexin.util.FileUtil;
import com.jiexin.util.XmlUtil;
import java.io.File;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @Author: Jay_Liu
 * @Description: XML Service
 * @Date: Created in 17:54 2018/9/7
 * @Modified By:
 */

@Service
@Slf4j
public class ReadXmlServiceImpl implements ReadXmlService {

    @Resource
    private DSHChangeMapper DSHChangeMapper;

    @Resource
    private MailService mailService;

    @Autowired
    private ExtractHandler extractHandler;


    /**
     * 读取XML文件的内容，持久化
     * @param xmlPath 待解析的XML文件
     * @param currentFileName 当前文件名称（TO00001.axml）
     * @param currentFilePath 待解析的文件路径(C:/ACS/axml/TO00001.axml)
     * @param successFilePath 解析成功存放的文件路径(C:/ACS/successBackup/TO00001.axml)
     * @param failFilePath 解析失败存放的文件路径(C:/ACS/failBackup/TO00001.axml)
     * @throws Exception
     */
    @Override
    public void readFileAndWriteInTable(String xmlPath, String currentFileName, String currentFilePath, String successFilePath, String failFilePath){
        File file = new File(xmlPath);
        SAXReader reader = new SAXReader();

        String changeNumber="";
        String atoNumber="";
        try {
            Document document = reader.read(file);
            if (document == null) {
                throw new Exception("failed to read file ,the failed file is " + currentFileName);
            }
            Element root = (Element) document.selectSingleNode("/*[name()='AgileData']");
            Element automatedTransferOrders = root.element("AutomatedTransferOrders");
            Element atoCoverPage = automatedTransferOrders.element("CoverPage");
            //自动编号
            atoNumber = atoCoverPage.elementText("AtoNumber");
            //变更单节点
            Element change = root.element(getChangeElement(root));
            //变更单封面节点
            Element changeCoverPage = change.element("CoverPage");
            //变更单创建者
            String changeOriginator = changeCoverPage.elementText("Originator");
//            String userId = changeOriginator.substring(changeOriginator.indexOf("(") + 1, changeOriginator.indexOf(")"));
            changeNumber = changeCoverPage.elementText("Number");
            log.info("The current change order number is ：{}", changeNumber);
            List<Element> affectedItems = change.elements("AffectedItems");
            if (affectedItems == null || affectedItems.size() == 0) {
                log.info("there is no affect items in the current change order：{}", changeNumber);
                //若此变更无受影响物件，则移动到successBackup中
                FileUtil.removeAXMLFile(currentFilePath, successFilePath, xmlPath);
                return;
            }
            //获取PID作为各表的共用主键
            long pid = DSHChangeMapper.findPid();
            //开始解析xml文件
            extractHandler.persist(file, pid,atoNumber,currentFileName);
            log.info("Successfully parse the XML file and insert it into the database");
            log.info("The pid is : {}", pid);
            //解析完成,删除Template的文件,并将文件移动到successBackup中
            FileUtil.removeAXMLFile(currentFilePath, successFilePath, xmlPath);
        } catch (Exception e) {
            e.printStackTrace();
            //邮件通知 TODO:
            mailService.sendMail("", "NOTIFICATION:Failed on processing Change["+atoNumber+"("+changeNumber+")] into temp table.", "{这封邮件由系统生成.不需要回复.}"+"\n"+"\n"+"Hi Administrator,"+"\n"+"\n"+"Failed on processing Change["+atoNumber+"("+changeNumber+")] in Agile System. Please Check Log."+"\n"+"\n"+"Regards,"+"\n"+"Agile");
            //删除Template的文件,并且将axml中的文件移动到failBackup中
            FileUtil.removeAXMLFile(currentFilePath, failFilePath, xmlPath);
            log.info("readFileAndWriteInTable failed, error message :{}", e);

        }
    }

    /**
     * 根据Root节点获取变更节点类型的名称
     * @param root root节点
     * @return 变更节点类型的名称
     */
    @Override
    public String getChangeElement(Element root) {
        if (XmlUtil.getElementByName(root, "ChangeOrders") != null) {
            root = XmlUtil.getElementByName(root, "ChangeOrders");
            return "ChangeOrders";
        } else if (XmlUtil.getElementByName(root, "ChangeRequests") != null) {
            root = XmlUtil.getElementByName(root, "ChangeRequests");
            return "ChangeRequests";
        } else if (XmlUtil.getElementByName(root, "Deviations") != null) {
            root = XmlUtil.getElementByName(root, "Deviations");
            return "Deviations";
        } else if (XmlUtil.getElementByName(root, "ManufacturerOrders") != null) {
            root = XmlUtil.getElementByName(root, "ManufacturerOrders");
            return "ManufacturerOrders";
        }  else if (XmlUtil.getElementByName(root, "SiteChangeOrders") != null) {
            root = XmlUtil.getElementByName(root, "SiteChangeOrders");
            return "SiteChangeOrders";
        }   else {
            root = XmlUtil.getElementByName(root, "StopShips");
            return "StopShips";
        }
    }

    @Override
    public Integer findPid() {
        return DSHChangeMapper.findPid();
    }


}
